package com.abc.robot01.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.abc.robot01.R
import com.abc.robot01.activity.CustomStyledTextField2
import com.abc.robot01.activity.CustomStyledTextField4
import com.abc.robot01.activity.MYBLACK
import com.abc.robot01.activity.MYBLACK_Percent10
import com.abc.robot01.activity.MYBLACK_Percent5
import com.abc.robot01.activity.MYBLUE
import com.abc.robot01.activity.MYWhilte_Percent40
import com.abc.robot01.activity.MyButton01
import com.abc.robot01.activity.MyDropdownMenu
import com.abc.robot01.activity.MyFont_Size
import com.abc.robot01.activity.MyRoundedCornerShape2
import com.abc.robot01.activity.SystemFragmentBackground
import com.abc.robot01.activity.TwoStateButton2
import com.abc.robot01.activity.TwoStateButton3
import com.abc.robot01.activity.mysp
import com.abc.robot01.activity.px
import com.abc.robot01.activity.startActivity
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.Customer
import com.abc.robot01.retrofit.bean.HouseType
import com.abc.robot01.vivemodel.CustomersViewModel
import com.bumptech.glide.integration.compose.GlideImage
import kotlinx.coroutines.launch

/**
 *  客户管理
 */
class CustomersFragment : Fragment() {
   val TAG="客户管理"
    private val viewModel: CustomersViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.init()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val composeView = ComposeView(requireContext()).apply {
            setContent {
                var show by remember { viewModel.show }
                SystemFragmentBackground {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(start = 30.px, top = 30.px),
                        verticalArrangement = Arrangement.Center,
                    ) {
                        SearchBar()
                        Spacer(modifier = Modifier.height(30.px))
                        ListHeader();
                        DataList2(::edit);
                    }
                }
                if (show) MyDialog() {
                    show = false
                }
            }
        }
        return composeView
    }

    @Composable
    fun ColumnScope.SearchBar() {
        val keyboardController = LocalSoftwareKeyboardController.current
        val selected1 = remember { viewModel.selected10 }
        val expanded1 = remember { viewModel.expanded1 }
        var height by remember { viewModel.height }
        val items: List<HouseType> by viewModel.question5List.collectAsState()

        Row {
            BasicText(
                text = "用户手机",
                style = TextStyle(
                    fontSize = MyFont_Size,
                    color = MYBLACK
                ),
                modifier = Modifier.align(Alignment.CenterVertically)
            )
            Spacer(modifier = Modifier.width(20.px))

            val customerPhone = remember { viewModel.customerPhone }
            CustomStyledTextField2(text = customerPhone, textColor = MYBLACK_Percent5) {
                viewModel.customerPhone.value = it
//                                viewModel.request(
//                                    customerPhone = it,
//                                    customerName = viewModel.customerName.value
//                                )
            }

            Spacer(modifier = Modifier.width(30.px))
            BasicText(
                text = "用户姓名",
                style = TextStyle(
                    fontSize = MyFont_Size,
                    color = MYBLACK
                ),
                modifier = Modifier.align(Alignment.CenterVertically)
            )
            Spacer(modifier = Modifier.width(20.px))
            val customerName = remember { viewModel.customerName }
            CustomStyledTextField2(text = customerName, textColor = MYBLACK_Percent5) {
                viewModel.customerName.value = it
//                                viewModel.request(
//                                    customerName = it,
//                                    customerPhone = viewModel.customerPhone.value
//                                )
            }

            Spacer(modifier = Modifier.width(30.px))
            BasicText(
                text = "状态",
                style = TextStyle(
                    fontSize = MyFont_Size,
                    color = MYBLACK
                ),
                modifier = Modifier.align(Alignment.CenterVertically)
            )
            Spacer(modifier = Modifier.width(20.px))

            Column {
                CustomStyledTextField4(selected1, textColor = MYBLACK_Percent5) {
                    expanded1.value = expanded1.value.not()
                }
                if (expanded1.value) {
                    MyDropdownMenu(expanded1, selected1,
                        selectedCode = viewModel.selectedStatusCode,
                        offsetY = 10.px,
                        height = height.px,
                        items2 = items.map { it.name to it.code }
                    )
                }
            }


//            CustomStyledTextField4(selected20,textColor = MYBLACK_Percent5) {
////                                expanded2.value = expanded2.value.not()
//            }


            Spacer(modifier = Modifier.width(47.px))
            MyButton01(
                text = "查询", size = DpSize(148.px, 50.px), textColor = Color.White,
                containerColor = MYBLUE, shape = RoundedCornerShape(25)
            ) {
                keyboardController?.hide()
                viewModel.load()
//                viewModel.width.value = viewModel.width.value+1;
//                Log.e("width"," viewModel.width.value:"+ viewModel.width.value)
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    private fun edit(id: Int) {
    }

    private fun delete(id: Int) {
    }


    @Composable
    fun DataList2(edit: (id: Int) -> Unit = { }) {
        val items: List<Customer> by viewModel.customerList.collectAsState()
        val width by remember { viewModel.width }
        Log.e("ListHeader", "width" + width);

//    val items = List(5) { "Item #$it" }
        LazyColumn(
            modifier = Modifier
                .width(1800.px)
                .background(Color.Transparent)
        ) {
            itemsIndexed(items) { index, item ->
                val isLastItem = index == items.lastIndex

                //不能使用row的原因是修改时间要和title对齐.
                Box(
                    modifier = Modifier
                        .padding(start = 0.px)
                        .height(90.px)
                        .width(1600.px)
                        .background(
                            color = MYWhilte_Percent40, // 背景颜色
                            shape = if (isLastItem) MyRoundedCornerShape2 else RoundedCornerShape(0)
                        )
                ) {
                    BasicText(
                        modifier = Modifier.offset(30.px, 33.px),
                        text = item.customerPhone,
                        style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                            fontSize = MyFont_Size,
                            color = MYBLACK
                        ),
                    )

                    BasicText(
                        maxLines=1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.offset(247.px, 33.px).width(180.px),
                        text = item.customerName,
                        style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                            fontSize = MyFont_Size,
                            color = MYBLACK
                        ),
                    )

                    BasicText(
                        modifier = Modifier.offset(440.px, 33.px),
                        text = item.customerStatusValue.toString(),
                        style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                            fontSize = MyFont_Size,
                            color = MYBLACK
                        ),
                    )

                    BasicText(
                        modifier = Modifier.offset((676 + 15).px, 33.px),
                        text = item.renderCount.toString(),
                        style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                            fontSize = MyFont_Size,
                            color = MYBLACK
                        ),
                    )

                    BasicText(
                        modifier = Modifier
                            .offset((700 + 74).px, 33.px)
                            .width(100.px),
                        text = item.renderTotalAmount.toString(),
                        style = TextStyle(
                            textAlign = TextAlign.Right,
//                          fontWeight = FontWeight.Bold,
                            fontSize = MyFont_Size,
                            color = MYBLACK
                        ),
                    )

                    BasicText(
                        modifier = Modifier.offset((947 + 20).px, 33.px),
                        text = item.latestCreateTime.split(" ")[0],
                        style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                            fontSize = MyFont_Size,
                            color = MYBLACK
                        ),
                    )

                    BasicText(
                        modifier = Modifier
                            .offset((1200 + 18).px, 33.px)
                            .width(80.px),
                        text = item.latestAmount.toString(),
                        style = TextStyle(
                            textAlign = TextAlign.Right,
                            fontSize = MyFont_Size,
                            color = MYBLACK
                        ),
                    )

                    Row(modifier = Modifier.offset(x = (1362 + 18).px, y = 21.px)) {
                        MyButton01(
                            shape = RoundedCornerShape(8.px),
                            text = "客户信息",
                            containerColor = MYBLUE,
                            size = DpSize(156.px, 48.px)
                        ) {
                            viewModel.selectedIndex.value = index;
                            viewModel.selectedCustomerPhone.value = item.customerPhone
                            viewModel.selectedCustomerName.value = item.customerName
                            //首次初始化为原来的名称.
                            viewModel.newCustomerName.value = item.customerName
                            Log.e(TAG,"item.customerStatusValue"+ item.customerStatusValue)

                            //设置客户状态
                            viewModel.reset()
                            if(item.customerStatus!=null){
                                viewModel.houseTypeList.find { it.code == item.customerStatus}?.isSelected = true
                            }


                            if(item.customerStatusValue==null){
                  Log.e(TAG,"item.customerStatusValue==null")
                                viewModel.selectedCustomerStatus.value=""
                            } else{
                                viewModel.selectedCustomerStatus.value = item.customerStatusValue
                            }

                            //界面文字显示状态值.
                            viewModel.selectedItemStatusValue.value =  viewModel.selectedCustomerStatus.value

                            viewModel.show.value = true
                        }
                        Spacer(modifier = Modifier.width(17.px))
                        MyButton01(
                            shape = RoundedCornerShape(8.px),
                            text = "渲染详情",
                            containerColor = MYBLUE,
                            size = DpSize(156.px, 48.px)
                        ) {
                            edit(index)
                            requireContext().startActivity<com.abc.robot01.flutter.CustomerRenderDetails> {
                                putExtra("customerName", item.customerName)
                                putExtra("customerPhone", item.customerPhone)
                                putExtra("totalAmount", item.renderTotalAmount.toString())
                            }
                        }
                    }

                }
                if (isLastItem.not()) {
                    HorizontalDivider(
                        modifier = Modifier.fillMaxWidth(),
                        thickness = 1.px,
                        color = MYBLACK_Percent10
                    )
                }
            }
        }
    }

    @Composable
    fun ListHeader() {
        val width by remember { viewModel.width }
        Log.e("ListHeader", "width" + width);
        val shape = RoundedCornerShape(
            topStart = 4.dp,
            topEnd = 4.dp,
            bottomStart = 0.dp,
            bottomEnd = 0.dp
        )

        Surface(
            modifier = Modifier
                .width(1800.px)
                .height(
                    56.px
                ),
            color = MYBLACK_Percent5,
            shape = shape
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.padding(start = 30.px)
            ) {
                BasicText(
                    text = "用户手机",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = MYBLACK
                    ),
                )
                Spacer(modifier = Modifier.width(120.px))
                BasicText(
                    text = "用户姓名",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = MYBLACK
                    ),
                )
                Spacer(modifier = Modifier.width((62 + 39).px))
                BasicText(
                    text = "用户状态",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = MYBLACK
                    ),
                )
                Spacer(modifier = Modifier.width(73.px))
                BasicText(
                    text = "渲染次数",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = MYBLACK
                    ),
                )
                Spacer(modifier = Modifier.width(70.px))
                BasicText(
                    text = "渲染金额",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = MYBLACK
                    ),
                )

                Spacer(modifier = Modifier.width(71.px))
                BasicText(
                    text = "最近渲染时间",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = MYBLACK
                    ),
                )

                Spacer(modifier = Modifier.width(68.px))
                BasicText(
                    text = "最近渲染金额",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = MYBLACK
                    ),
                )

                Spacer(modifier = Modifier.width(221.px))
                BasicText(
                    text = "操作",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = MYBLACK
                    ),
                )


            }
        }

    }


    @Composable
    fun MyDialog(onConfirm: () -> Unit = {}, onDismissRequest: () -> Unit = {}) {
        val houseTypeList = remember { viewModel.houseTypeList }
        Dialog(
            properties = DialogProperties(
                usePlatformDefaultWidth = false,
                dismissOnBackPress = false, // 禁用返回按钮
//                dismissOnClickOutside = false // 禁用点击外部关闭对话框
            ),
            onDismissRequest = { onDismissRequest() }) {
            Box(
                modifier = Modifier
                    .background(color = Color.White, shape = RoundedCornerShape(20.px))
                    .size(680.px, 517.px)
                    .padding(30.px),
            ) {
                Column {
                    BasicText(
                        text = "客户信息",
                        style = TextStyle(
                            fontWeight = FontWeight.Bold,
                            fontSize = 30.mysp,
                            color = MYBLACK
                        ),
                    )

                    Spacer(modifier = Modifier.height(30.px))

                    Row(verticalAlignment = Alignment.CenterVertically) {
                        BasicText(
                            text = "客户手机",
                            style = TextStyle(
                                fontSize = 24.mysp,
                                color = MYBLACK
                            ),
                        )
                        Spacer(modifier = Modifier.width(20.px))
                        val customerPhone = remember { viewModel.selectedCustomerPhone }
                        CustomStyledTextField2(
                            size = DpSize(504.px, 50.px),
                            enabled = false,
                            text = customerPhone, textColor = MYBLACK_Percent5
                        )

                    }

                    Spacer(modifier = Modifier.height(30.px))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        BasicText(
                            text = "客户姓名",
                            style = TextStyle(
                                fontSize = 24.mysp,
                                color = MYBLACK
                            ),
                        )
                        Spacer(modifier = Modifier.width(20.px))
                        val newCustomerName = remember { viewModel.newCustomerName }
                        CustomStyledTextField2(
                            size = DpSize(504.px, 50.px),
                            text = newCustomerName, textColor = MYBLACK_Percent5
                        )
                    }
                    Spacer(modifier = Modifier.height(30.px))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        BasicText(
                            text = "客户状态",
                            style = TextStyle(
                                fontSize = 24.mysp,
                                color = MYBLACK
                            ),
                        )
                        Spacer(modifier = Modifier.width(20.px))
                        val selectedItemStatusValue = remember { viewModel.selectedItemStatusValue }
                        CustomStyledTextField2(
                            size = DpSize(504.px, 50.px),
                            enabled = false,
                            text = selectedItemStatusValue, textColor = MYBLACK_Percent5
                        )
                    }
                    Spacer(modifier = Modifier.height(30.px))
                    Row {
                        Spacer(modifier = Modifier.width(96.px))
                        houseTypeList.forEach {
                            Spacer(modifier = Modifier.width(12.px))
                            TwoStateButton3(houseTypeList, it.label) {
                                viewModel.selectedItemStatusCode.value = it.second
                                viewModel.selectedItemStatusValue.value = it.first
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(30.px))

                Row {
                    Spacer(modifier = Modifier.weight(10.0f))
                    MyButton01(
                        fontSize = 30.mysp,
                        text = "取消", size = DpSize(160.px, 70.px), textColor = MYBLACK,
                        containerColor = MYBLACK_Percent10, shape = RoundedCornerShape(10.px)
                    ) {
                        onDismissRequest()
                    }
                    Spacer(modifier = Modifier.width(20.px))
                    MyButton01(
                        fontSize = 30.mysp,
                        text = "确认", size = DpSize(160.px, 70.px), textColor = Color.White,
                        containerColor = MYBLUE, shape = RoundedCornerShape(10.px)
                    ) {
                        Log.e("0123", "" + houseTypeList.filter { it.isSelected }.toString());
                        if (viewModel.newCustomerName.value.trim() == "") {
                            Toast.makeText(
                                this@CustomersFragment.activity,
                                "请输入客户姓名",
                                Toast.LENGTH_LONG
                            ).show()
                            return@MyButton01
                        }
                        lifecycleScope.launch {
                            viewModel.updateCustomer()
                            onDismissRequest()
                        }
                    }
                }
            }
            }
        }
    }
}
